package com.forward.uploadapp.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.forward.uploadapp.R;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by forward on 2017/12/16.
 */
public class FileDisplayAdapter extends BasicAdapter {
    private List<File> mDatas;

    public FileDisplayAdapter(Context context, List<File> datas) {
        super(context);
        mDatas = datas;
    }

    @Override
    public int getCount() {
        return mDatas == null ? 0 : mDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return mDatas == null ? null : mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext)
                    .inflate(R.layout.file_horizontal, viewGroup, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        File file = mDatas.get(position);
        if (file.isDirectory()) {
            holder.fileIcon.setImageDrawable(
                    mContext.getResources().getDrawable(R.mipmap.file_type_folder));
        } else {
            holder.fileIcon.setImageDrawable(
                    mContext.getResources().getDrawable(R.mipmap.file_type_file));
        }
        holder.fileName.setText(file.getName());
        return convertView;
    }

    public void refresh() {
        Collections.sort(mDatas, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if ((o1.isDirectory() && o2.isDirectory()) || (o1.isFile() && o2.isFile())) {
                    return o1.getName().compareTo(o2.getName());
                } else if (o1.isFile() && o2.isDirectory()){
                    return 1;
                }else {
                    return -1;
                }
            }
        });
        notifyDataSetChanged();
    }

    private class ViewHolder {
        private ImageView fileIcon;
        private TextView fileName;

        public ViewHolder(View view) {
            fileIcon = (ImageView) view.findViewById(R.id.fileIcon);
            fileName = (TextView) view.findViewById(R.id.fileName);
        }
    }
}
